package com.mizhiquan.util;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.mizhiquan.common.Const;
import com.mizhiquan.dao.EmailCodeMapper;
import com.mizhiquan.dao.PhoneCodeMapper;
import com.mizhiquan.pojo.EmailCode;
import com.mizhiquan.pojo.PhoneCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.UUID;


/**
 * Created by Shane on 2017/6/25.
 */
@Component
public class SendCodeUtil {

    @Autowired
    private PhoneCodeMapper phoneCodeMapper;

    @Autowired
    private EmailCodeMapper emailCodeMapper;

    public static SendCodeUtil sendCodeUtil;

    @PostConstruct
    public void init(){
        sendCodeUtil = this;
    }

    /**
     * 阿里云发送验证码邮件
     * @param toEmail 发送到的邮箱地址
     * @param time  超时时间
     */
    public static Boolean sendEmail(String toEmail , int time ,String userId,String outerId){
        String uuid = UUID.randomUUID().toString().toUpperCase(); //获取UUID并转化为String对象
        uuid = uuid.replace("-", "");//因为UUID本身为32位只是生成时多了“-”，所以将它们去点就可
        //TODO: 切记！确定激活邮件的接口链接，即link
        String link=Const.APP_URL+"user/activate.do?token="+uuid+"&id="+outerId+"&type=email&account="+toEmail;
        //入库操作
        EmailCode emailCode = new EmailCode(uuid,toEmail,new Date(),Const.EMAILTimeOut,false,userId,outerId);
        sendCodeUtil.emailCodeMapper.insert(emailCode);
        //通过模板生成邮件正文
        String content = getEmailContent(link,time,Const.SDF_DAY.format(new Date()));
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Const.accessKeyId, Const.accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            request.setAccountName("noreply@mizhiquan.com");
            request.setFromAlias(Const.APP_NAME);
            request.setAddressType(1);
            request.setReplyToAddress(false);
            request.setToAddress(toEmail);
            request.setSubject("账户激活邮件");
            request.setHtmlBody(content);
            client.getAcsResponse(request);
            return true;
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ServerException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 阿里云发送短信验证码
     * @param phone 手机号
     * @param time 有效时间（分钟）
     * @param smsTemplet 短信模板代码，决定了短信内容
     */
    public static Boolean sendSMSCode(String phone, int time, String userId,Const.SMSTemplet smsTemplet) {
        //生成6位随机数
        String code = RandomCodeUtil.getRandomNum(6,true);
        //生成phoneCode对象并存到数据库中
        PhoneCode phoneCode = new PhoneCode(code,phone,new Date(),time,false,userId);
        sendCodeUtil.phoneCodeMapper.insert(phoneCode);
        //开始调用阿里云短信接口发送短信
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Const.accessKeyId, Const.accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        } catch (com.aliyuncs.exceptions.ClientException e1) {
            e1.printStackTrace();
        }
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        try {
            request.setSignName(Const.APP_NAME);
            request.setTemplateCode(smsTemplet.getValue());
            String param = "{\"code\":\""+code+"\",\"time\":\""+time+"\"}";
            request.setTemplateParam(param);
            request.setPhoneNumbers(phone);
            SendSmsResponse httpResponse = client.getAcsResponse(request);
            if("OK".equals(httpResponse.getCode()))
                return true;
            else
                return false;
        } catch (ServerException e) {
            e.printStackTrace();
        }
        catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    //邮件内容模板
    private static String getEmailContent(String link,int timeout,String date){
        String content = "<p>\n" +
                "    您好，感谢您注册觅知圈，请在"+timeout+"分钟内点击以下链接完成注册(<a href='"+link+"'>"+link+"</a>)，如非本人操作，请您忽略。\n" +
                "</p>\n" +
                "<p style=\"text-align: right;\">\n" +
                "    觅知圈团队\n" +
                "</p>\n" +
                "<p style=\"text-align: right;\">\n" +
                "    "+date+"\n" +
                "</p>";
        return content;
    }

}
